//
//  AlphaFrameFilter.swift
//  AlphaVideo
//
//  Created by kou on 2022/5/25.
//  Copyright © 2022 kou. All rights reserved.
//

import CoreImage

class AlphaFrameFilter: CIFilter {
    static var kernel: CIColorKernel? = {
        if #available(iOS 11.0, *) {
            guard let url = Bundle.main.url(forResource: "default", withExtension: "metallib"), let date = try? Data(contentsOf: url), let Color = try? CIColorKernel(functionName: "maskVideoMetal", fromMetalLibraryData: date) else {
                return CIColorKernel(source: """
                kernel vec4 alphaFrame(__sample s, __sample m) {
                  return vec4(s.rgb, m.r);
                }
                """)
            }
            return Color
        } else {
            return CIColorKernel(source: """
            kernel vec4 alphaFrame(__sample s, __sample m) {
              return vec4(s.rgb, m.r);
            }
            """)
        }

    }()

    var inputImage: CIImage?
    var maskImage: CIImage?

    override var outputImage: CIImage? {
        let kernel = AlphaFrameFilter.kernel!
        guard let inputImage = inputImage, let maskImage = maskImage else {
            return nil
        }
        let args = [inputImage as AnyObject, maskImage as AnyObject]
        return kernel.apply(extent: inputImage.extent, arguments: args)
    }
}
